package com.yuan.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuan.listener.ExcelDictDTOListener;
import com.yuan.mapper.DictMapper;
import com.yuan.pojo.dto.ExcelDictDTO;
import com.yuan.pojo.entity.Dict;
import com.yuan.service.DictService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author yuan
 * @since 2021-11-08
 */
@Slf4j
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Resource
    private DictMapper dictMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void importData(InputStream inputStream) {
        // 这里需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
        EasyExcel.read(inputStream, ExcelDictDTO.class, new ExcelDictDTOListener(dictMapper)).sheet().doRead();
        log.info("importData finished");
    }

    @Override
    public List<ExcelDictDTO> listDictData() {

        // 获取dict表中的全部数据
        List<Dict> dicts = dictMapper.selectList(null);
        List<ExcelDictDTO> list = new ArrayList<>(dicts.size());
        for (Dict dict : dicts) {
            ExcelDictDTO excelDictDTO = new ExcelDictDTO();
            excelDictDTO.setId(dict.getId());
            excelDictDTO.setParentId(dict.getParentId());
            excelDictDTO.setName(dict.getName());
            excelDictDTO.setValue(dict.getValue());
            excelDictDTO.setDictCode(dict.getDictCode());
            list.add(excelDictDTO);
        }
        return list;
    }

    @Override
    public List<Dict> listByParentId(Long parentId) {

        try {
            // 首先查询redis中是否存在数据列表
            List<Dict> dictList =  (List<Dict>)redisTemplate.opsForValue().get("dictList:" + parentId);
            if (dictList != null){
                log.info("从redis中取值");
                // 如果存在则从redis中直接返回数据列表
                return dictList;
            }
        }catch (Exception e){
            log.error("redis服务器异常：" + ExceptionUtils.getStackTrace(e));//此处不抛出异常，继续执行后面的代码
        }


        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",parentId);
        List<Dict> list = dictMapper.selectList(queryWrapper);
        for (Dict dict : list) {
            // 判断当前节点是否有子节点
            boolean hasChildren = this.hasChildren(dict.getId());
            dict.setHasChildren(hasChildren);
        }

        //将数据存入redis
        try {
            //向数据库中存储string类型的键值对, 过期时间5分钟
            redisTemplate.opsForValue().set("dictList:" + parentId, list, 5, TimeUnit.MINUTES);
            log.info("数据存入redis");
        } catch (Exception e) {
            log.error("redis服务器异常：" + ExceptionUtils.getStackTrace(e));//此处不抛出异常，继续执行后面的代码
        }
        return list;
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.eq("dict_code", dictCode);

        Dict dict = baseMapper.selectOne(dictQueryWrapper);
        return this.listByParentId(dict.getId());
    }

    @Override
    public String getNameByParentDictCodeAndValue(String dictCode, Integer value) {
        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<Dict>();
        dictQueryWrapper.eq("dict_code", dictCode);
        Dict parentDict = baseMapper.selectOne(dictQueryWrapper);

        if(parentDict == null) {
            return "";
        }

        dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper
                .eq("parent_id", parentDict.getId())
                .eq("value", value);
        Dict dict = baseMapper.selectOne(dictQueryWrapper);

        if(dict == null) {
            return "";
        }
        return dict.getName();
    }

    /**
     * 判断当前节点是否有子节点
     * @param id
     * @return
     */
    private boolean hasChildren(Long id){
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",id);
        Integer count = baseMapper.selectCount(queryWrapper);
        if (count.intValue() > 0) return true;
        return false;

    }
}
